package com.alibaba.citrus.cr.b2b.trade.order.functions.deliveryOrder.factory;


import com.alibaba.citrus.cr.b2b.trade.order.repository.DeliverOrderWriteRepository;
import com.alibaba.citrus.cr.b2b.trade.order.functions.deliveryOrder.entity.DeliveryOrderWriteEntity;
import com.alibaba.citrus.cr.b2b.trade.order.functions.utils.ModifyDeliverOrderConverter;
import com.alibaba.citrus.cr.common.util.SpringContextUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.epoch.app.crb2btradecenter.dto.OrderDetailDTO;
import com.epoch.app.crb2btradecenter.dto.Packagedetails;
import com.epoch.app.crb2btradecenter.dto.request.SendOutGoodsRequest;
import com.epoch.app.crb2btradecenter.sdo.DeliverOrderSDO;
import org.apache.commons.collections.MapUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

public class DeliveryOrderWriteFactory {

    private static DeliverOrderWriteRepository deliverOrderWriteRepository;


    static {
        deliverOrderWriteRepository = SpringContextUtil.getBean(DeliverOrderWriteRepository.class);
    }

    public static DeliveryOrderWriteEntity modifyStatus(SendOutGoodsRequest request , Map<String, OrderDetailDTO> goodsAndOrderDetailDTOMap) {

        //已发货数量之和
        int shippedQuantityCountSum = 0;
        //货品数量之和
        int quantityCountSum = 0 ;

        if (!CollectionUtils.isEmpty(request.getPackageDetailsList())) {
            for(Packagedetails packageDetailsList : request.getPackageDetailsList()){
                if (!MapUtils.isEmpty(packageDetailsList.getOrderLineQuantity())) {
                    for (String  key :packageDetailsList.getOrderLineQuantity().keySet()){
                        if (!StringUtils.isEmpty(goodsAndOrderDetailDTOMap.get(key).getQuantity())) {
                            //货品数量
                            int quantity = Integer.parseInt(goodsAndOrderDetailDTOMap.get(key).getQuantity());
                            quantityCountSum = quantityCountSum + quantity;
                        }
                        if (!StringUtils.isEmpty(packageDetailsList.getOrderLineQuantity().get(key))) {
                            //发货数量
                            int shippedQuantity = Integer.parseInt(packageDetailsList.getOrderLineQuantity().get(key));
                            shippedQuantityCountSum  = shippedQuantityCountSum + shippedQuantity;
                        }
                    }

                }
            }
        }
        DeliverOrderSDO deliverOrderSDO = null;
        if (shippedQuantityCountSum == quantityCountSum) {
            deliverOrderSDO = ModifyDeliverOrderConverter.converter(request);
        } else if (shippedQuantityCountSum < quantityCountSum){
            deliverOrderSDO = ModifyDeliverOrderConverter.converterOne(request);
        }
        DeliveryOrderWriteEntity deliveryOrderWriteEntity = DeliveryOrderWriteEntity.of(deliverOrderSDO);
        return deliveryOrderWriteEntity;
    }
}
